<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch"  label-width="100px">
      <el-form-item label="退料单编号" prop="rtCode" >
        <el-input
          v-model="queryParams.rtCode"
          placeholder="请输入退料单编号"
          clearable
          @keyup.enter="handleQuery"
   
        />
      </el-form-item>
      <el-form-item label="退料单名称" prop="rtName">
        <el-input
          v-model="queryParams.rtName"
          placeholder="请输入退料单名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产工单编码" prop="workorderCode">
        <el-input
          v-model="queryParams.workorderCode"
          placeholder="请输入生产工单编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary"  plain icon="Plus"   @click="handleAdd"  v-hasPermi="['issue:issue:add']" >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['issue:issue:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['issue:issue:remove']"
        >删除</el-button>
      </el-col>
      
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="issueList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="退料单编号" align="center" prop="rtCode" />
      <el-table-column label="退料单名称" align="center" prop="rtName" />
      <el-table-column label="生产工单编码" align="center" prop="workorderCode" />
      <el-table-column label="退料日期" align="center" prop="rtDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.rtDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['issue:issue:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['issue:issue:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改生产退料对话框 -->
     <el-dialog :title="title" v-model="open" width="900px" append-to-body @close="resetDialogForm" >
      <el-row :gutter="15">
        <el-form ref="issueRef1" :model="form" :rules="rules" size="default" label-width="100px">
          <el-col :span="24">
            <el-row gutter="15">
              <el-col :span="10">
                <el-form-item label="退货单编号" prop="rtCode" >
                  <el-input v-model="form.rtCode" type="text" placeholder="请输入退货单编号"
                    :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
                <!-- 自动生成文字移到开关后面 -->
              <el-switch 
                v-model="autoGenerateCode" 
                style="margin-left: 10px;"
                @change="handleCodeSwitchChange" 
              ></el-switch>
              <span style="margin-left: 5px;">自动生成</span>

              <el-col :span="11">
                <el-form-item label="退货单名称" prop="rtName">
                  <el-input v-model="form.rtName" type="text" placeholder="请输入退货单名称" clearable
                    :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-row gutter="15">
              <el-col :span="10">
                <el-form-item label="生产工单" prop="workorderCode">
                  <el-input v-model="form.workorderCode" type="text" placeholder="请选择生产工单" clearable disabled
                    :style="{width: '100%'}"></el-input>
                    <el-icon @click="kaii" style="border: 1px solid #DCDFE6;width: 30px;height: 30px;background-color: #F5F7FA;cursor: pointer;position: relative;left:160px;top: -31px;"><Search /></el-icon>

                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="退料日期" prop="rtDate">
                  <el-date-picker v-model="form.rtDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                    :style="{width: '100%'}" placeholder="请选择退料日期" clearable></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
           <el-col :span="10">
            <el-form-item label="仓库位置" >
              <el-cascader v-model="value1" :options="formattedOptions" :style="{width: '100%'}" placeholder="请选择仓库"
                clearable></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"
                :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
       <el-card style="max-width: 900px" v-show="flag">
          <template #header>
            <div class="card-header">
              <span><strong style="font: 90px;">物料信息</strong></span>
             
            </div>
          </template>
          <div>
            
                <el-row :gutter="10" class="mb8">
                  <el-col :span="1.5">
                    <el-button
                      type="primary"
                      plain
                      icon="Plus"
                      @click="handleAdd2"
                      v-hasPermi="['line:line:add']"
                    >新增</el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button
                      type="success"
                      plain
                      icon="Edit"
                      :disabled="single4"
                      @click="handleUpdate3"
                      v-hasPermi="['line:line:edit']"
                    >修改</el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button
                      type="danger"
                      plain
                      icon="Delete"
                      :disabled="multiple4"
                      @click="handleDelete3"
                      v-hasPermi="['line:line:remove']"
                    >删除</el-button>
                  </el-col>
                  
                  <right-toolbar v-model:showSearch="showSearch3" @queryTable="getList3(nowId)"></right-toolbar>
                </el-row>

                <el-table v-loading="loading3" :data="lineList" @selection-change="handleSelectionChange4">
                  <el-table-column type="selection" width="55" align="center" />
                  <el-table-column label="物料编码" align="center" prop="itemCode" />
                  <el-table-column label="物料名称" align="center" prop="itemName" />
                  <el-table-column label="规格型号" align="center" prop="specification" />
                  <el-table-column label="单位" align="center" prop="unitOfMeasure" />
                  <el-table-column label="退料数量" align="center" prop="quantityRt" />
                  <el-table-column label="领料批次号" align="center" prop="batchCode" />
                  <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px">
                    <template #default="scope">
                      <el-button link type="primary" icon="Edit" @click="handleUpdate3(scope.row)" v-hasPermi="['line:line:edit']">修改</el-button>
                      <el-button link type="primary" icon="Delete" @click="handleDelete3(scope.row)" v-hasPermi="['line:line:remove']">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                
                <pagination
                  v-show="total4>0"
                  :total="total4"
                  v-model:page="queryParams3.pageNum"
                  v-model:limit="queryParams3.pageSize"
                  @pagination="getList3(nowId)"
                />

                <!-- 添加或修改生产退料单行对话框 -->
                <el-dialog v-model="open3"  :title="title4" width="900px" @close="handleDialogClose3">
                  <el-row :gutter="15">
                    <el-form ref="formRef" :model="form1" :rules="rules3" size="default" label-width="120px">
                      <el-col :span="24">
                        <el-row gutter="15">
                          <el-col :span="8">
                            <el-form-item label="物料编码" prop="itemCode">
                              <el-input v-model="form1.itemCode" type="text" placeholder="请输入物料编码" clearable disabled
                                :style="{width: '100%'}"></el-input>
                              <el-icon @click="kaii1" style="border: 1px solid #DCDFE6;width: 30px;height: 30px;background-color: #F5F7FA;cursor: pointer;position: relative;left:155px;top:-31px"><Search /></el-icon>

                            </el-form-item>
                          </el-col>
                          <el-col :span="8">
                            <el-form-item label="物料名称" prop="itemName">
                              <el-input v-model="form1.itemName" type="text" placeholder="请输入物料名称" clearable disabled
                                :style="{width: '100%'}"></el-input>
                            </el-form-item>
                          </el-col>
                          <el-col :span="8">
                            <el-form-item label="单位" prop="unitOfMeasure">
                              <el-input v-model="form1.unitOfMeasure" type="text" placeholder="请输入单位" clearable disabled
                                :style="{width: '100%'}"></el-input>
                            </el-form-item>
                          </el-col>
                        </el-row>
                      </el-col>
                      
                      <el-col :span="20">
                        <el-form-item label="规格型号" prop="specification">
                          <el-input v-model="form1.specification" type="text" placeholder="请输入规格型号" clearable disabled
                            :style="{width: '100%'}"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="24">
                        <el-row gutter="15">
                          <el-col :span="11">
                            <el-form-item label="批次号" prop="batchCode" >
                              <el-input v-model="form1.batchCode" type="text"  clearable disabled
                                :style="{width: '100%'}"></el-input>
                            </el-form-item>
                          </el-col>
                          <el-col :span="8">
                            <el-form-item label="退料数量" prop="quantityRt">
                              <el-input v-model="form1.quantityRt" type="text" placeholder="请输入退料数量" clearable
                                :style="{width: '100%'}"></el-input>
                            </el-form-item>
                          </el-col>
                        </el-row>
                      </el-col>
                    </el-form>
                  </el-row>
                  <template #footer>
                    <el-button @click="cancel4">取消</el-button>
                    <el-button type="primary" @click="submitForm3">确定</el-button>
                  </template>
                </el-dialog>

                <!-- 物料选择 -->
                <el-dialog v-model="open4" width="1200px"   @close="handleDialogClose1">
                  <el-container>
                    <el-aside width="200px" style="background-color: white;">
                    <el-table
                      style="border: none;"
                      v-if="refreshTable"
                      :data="type1List"
                      row-key="itemTypeId"
                      :default-expand-all="isExpandAll"
                      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                      @row-click="handleCategoryClick" > <!-- 新增：点击分类行触发查询 -->
                      <el-table-column  align="center" prop="itemTypeName" />
                    </el-table>
                      </el-aside>
                      <el-main>
                    <el-form :model="queryParams2" ref="queryRef" :inline="true" v-show="showSearch2" label-width="68px">
                      <el-form-item label="物料编码" prop="itemCode">
                        <el-input
                          v-model="queryParams2.itemCode"
                          placeholder="请输入产品物料编码"
                          clearable
                          @keyup.enter="handleQuery2"
                        />
                      </el-form-item>
                      <el-form-item label="物料名称" prop="itemName">
                        <el-input
                          v-model="queryParams2.itemName"
                          placeholder="请输入产品物料名称"
                          clearable
                          @keyup.enter="handleQuery2"
                        />
                      </el-form-item>
                      <el-form-item label="批次号" prop="batchCode">
                        <el-input
                          v-model="queryParams2.batchCode"
                          placeholder="请输入批次号"
                          clearable
                          
                          @keyup.enter="handleQuery2"
                        />
                      </el-form-item>
                      <el-form-item label="仓库" prop="warehouseName">
                        <el-input
                          v-model="queryParams2.warehouseName"
                          placeholder="请输入仓库"
                          clearable
                          @keyup.enter="handleQuery2"
                        />
                      </el-form-item>
                      <el-form-item label="库区" prop="locationName">
                        <el-input
                          v-model="queryParams2.locationName"
                          placeholder="请输入库区"
                          clearable
                          @keyup.enter="handleQuery2"
                        />
                      </el-form-item>
                      <el-form-item label="库位" prop="areaName">
                        <el-input
                          v-model="queryParams2.areaName"
                          placeholder="请输入库位"
                          clearable
                          @keyup.enter="handleQuery2"
                        />
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery2">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery2">重置</el-button>
                      </el-form-item>
                    </el-form>

                  <el-table v-loading="loading2" ref="userTableRef" :data="userList1" @selection-change="handleRadioChange2">
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column label="物料编码" align="center" prop="itemCode" />
                    <el-table-column label="物料名称" align="center" prop="itemName" />
                    <el-table-column label="规格型号" align="center" prop="specification" />
                    <el-table-column label="在库数量" align="center" prop="quantityOnhand" />
                    <el-table-column label="单位" align="center" prop="unitOfMeasure" />
                    <el-table-column label="批次号" align="center" prop="batchCode" />
                    <el-table-column label="仓库" align="center" prop="warehouseName" />
                    <el-table-column label="库区" align="center" prop="locationName" />
                    <el-table-column label="库位" align="center" prop="areaName" />
                    <el-table-column label="入库时间" align="center" prop="recptDate" width="180">
                      <template #default="scope">
                        <span>{{ parseTime(scope.row.recptDate, '{y}-{m}-{d}') }}</span>
                      </template>
                    </el-table-column>
                    
                  </el-table>
                  
                  <pagination
                    v-show="total2>0"
                    :total="total2"
                    v-model:page="queryParams2.pageNum"
                    v-model:limit="queryParams2.pageSize"
                    @pagination="getList2"
                  />
                </el-main>
                </el-container>
                <el-button style="margin-left: 950px;" type="primary" @click="confirmSelectedItem2">确 认</el-button>
                <el-button @click="cancel1">关 闭</el-button>
                </el-dialog>
              </div>
        </el-card>
    </el-dialog>

<!-- 工单选择 -->
     <el-dialog title="工单选择" v-model="open2" width="1200px" class="tankuang" append-to-body   @close="handleDialogClose">
      <el-form :model="queryParams1" ref="queryRef" :inline="true" v-show="showSearch1" label-width="68px">
          <el-form-item label="工单编码" prop="workorderCode">
            <el-input
              v-model="queryParams1.workorderCode"
              placeholder="请输入工单编码"
              clearable
              @keyup.enter="handleQuery1"
            />
          </el-form-item>
          <el-form-item label="工单名称" prop="workorderName">
            <el-input
              v-model="queryParams1.workorderName"
              placeholder="请输入工单名称"
              clearable
              @keyup.enter="handleQuery1"
            />
          </el-form-item>
        
          <el-form-item label="产品编号" prop="productCode">
            <el-input
              v-model="queryParams1.productCode"
              placeholder="请输入产品编号"
              clearable
              @keyup.enter="handleQuery1"
            />
          </el-form-item>
          <el-form-item label="产品名称" prop="productName">
            <el-input
              v-model="queryParams1.productName"
              placeholder="请输入产品名称"
              clearable
              @keyup.enter="handleQuery1"
            />
          </el-form-item>
          <el-form-item label="客户名称" prop="clientName">
            <el-input
              v-model="queryParams1.clientName"
              placeholder="请输入客户名称"
              clearable
              @keyup.enter="handleQuery1"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery1">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery1">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table v-loading="loading1" ref="tableRef" :data="workorderList" @selection-change="handleSelectionChange1">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="工单编码" align="center" prop="workorderCode" />
          <el-table-column label="工单名称" align="center" prop="workorderName" />
          <el-table-column label="工单来源" align="center" prop="orderSource" />
          <el-table-column label="订单编号" align="center" prop="orderId" />
          <el-table-column label="产品编号" align="center" prop="productCode" />
          <el-table-column label="产品名称" align="center" prop="productName" />
          <el-table-column label="规格型号" align="center" prop="productSpc" />
          <el-table-column label="单位" align="center" prop="unitOfMeasure" />
          <el-table-column label="工单数量" align="center" prop="quantity" />
          <el-table-column label="客户编码" align="center" prop="clientCode" />
          <el-table-column label="客户名称" align="center" prop="clientName" />
          <el-table-column label="需求日期" align="center" prop="requestDate" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.requestDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
        </el-table>
        
        <pagination
          v-show="total1>0"
          :total="total1"
          v-model:page="queryParams1.pageNum"
          v-model:limit="queryParams1.pageSize"
          @pagination="getList1"
        />
        <div style="position: relative;left:-500px;">
          <el-button style="margin-left: 950px;" type="primary" @click="confirmSelectedItem">确 认</el-button>
        <el-button @click="cancel3">关 闭</el-button>
        </div>
        
     </el-dialog>
  </div>
</template>

<script setup name="Issue">
import { listLine1, getLine, delLine, addLine, updateLine } from "@/api/line/line"


const lineList = ref([])
const open3 = ref(false)
const open4=ref(false)
const loading3 = ref(true)
const showSearch3 = ref(true)
const ids3 = ref([])
const single4 = ref(true)
const multiple4 = ref(true)
const total4 = ref(0)
const title4 = ref("")

const data3 = reactive({
  form1: {

  },
  queryParams3: {
    pageNum: 1,
    pageSize: 10,
  },
   rules3: {
    itemCode: [{
      required: true,
      message: '请输入物料编码',
      trigger: 'blur'
    }],
    
    unitOfMeasure: [],
   
    specification: [],
    batchCode: [],
    quantityRt: [{
      required: true,
      message: '请输入退料数量',
      trigger: 'blur'
    }],

  }
})

//查看物料
 function kaii1() {
    open4.value=true
}


import { listStock} from "@/api/stock/stock"

const selectedUser = ref([])
const loading2 = ref(true)
const showSearch2 = ref(true)
const ids5 = ref([])
const single2 = ref(true)
const multiple2 = ref(true)
const total2 = ref(0)

const data2 = reactive({
  form: {},
  queryParams2: {
    pageNum: 1,
    pageSize: 10,
    itemCode: null,
    itemName: null,
    itemTypeName: null,
     itemTypeId: 1,  // 新增：用于存储选中的物料分类ID
  },
})

const { queryParams2} = toRefs(data2)
const userList1 = ref([]);
/** 查询物料产品管理列表 */
function getList2() {
  loading2.value = true
  listStock(queryParams2.value).then(response => {
    userList1.value = response.rows
    total2.value = response.total
    loading2.value = false
  })
}

// 表单重置
function reset1() {
  form1.value = {
    itemId: null,
    itemCode: null,
    itemName: null,
    specification: null,
    unitOfMeasure: null,
    itemOrProduct: null,
    itemTypeId: null,
    itemTypeCode: null,
    itemTypeName: null,
    enableFlag: null,
    safeStockFlag: null,
    minStock: null,
    maxStock: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
     itemTypeId: 1,
  }
  proxy.resetForm("itemRef")
}

/** 搜索按钮操作 */
function handleQuery2() {
  queryParams2.value.pageNum = 1
  getList2()
}

/** 重置按钮操作 */
function resetQuery2() {
  proxy.resetForm("queryRef")
    // 清除分类ID查询条件
  queryParams2.value.itemTypeId = 1
  handleQuery2()
}


getList2()



const type1List = ref([])
const isExpandAll = ref(true)
const refreshTable = ref(true)


const data4 = reactive({
  queryParams4: {
  },
})

const { queryParams4 } = toRefs(data4)

/** 查询物料分类列表 */
function getList6() {
  loading2.value = true
  listType1(queryParams4.value).then(response => {
    type1List.value = proxy.handleTree(response.data, "itemTypeId", "parentTypeId")
    loading2.value = false
  })
}
getList6()


//下拉表
import { listType1} from "@/api/type1/type1"

//处理物料分类点击事件 */
function handleCategoryClick(row) {
  // 设置选中的分类ID到查询参数
  queryParams2.value.itemTypeId = row.itemTypeId
  // 重置页码为1
  queryParams2.value.pageNum = 1
  // 执行查询
  getList2()
}

function handleRadioChange2(selection) {
  ids5.value = selection.map(item => item.workorderId)
  single2.value = selection.length != 1
  multiple2.value = !selection.length
    selectedUser.value = selection.length > 0 ? selection[0] : null;

}
// 选中按钮
function confirmSelectedItem2() {
  if (!selectedUser.value) {
    proxy.$modal.msgWarning("请选择一个物料");
    return;
  }
  // console.log("表单");
  // console.log(selectedUser.value);
  // 将选中的物料信息回填到表单
  form1.value.materialStockId = selectedUser.value.materialStockId;
  form1.value.itemId = selectedUser.value.itemId;
  form1.value.itemCode = selectedUser.value.itemCode;
   form1.value.batchCode = selectedUser.value.batchCode;
   form1.value.itemName = selectedUser.value.itemName;
   form1.value.specification = selectedUser.value.specification;
    form1.value.unitOfMeasure = selectedUser.value.unitOfMeasure;
  // 关闭物料选择框，返回工单表单
  open4.value = false;
  //open.value = true;

}

const userTableRef = ref(null); // 用于获取el-table实例
// 对话框关闭时的处理方法
const handleDialogClose1 = () => {
  open4.value = false;
 // open.value = true;
  if (userTableRef.value) {
    userTableRef.value.clearSelection(); // 清空表格多选框选中状态
  }
};
const handleDialogClose3=()=>{
  open3.value = false; // 只关闭内层弹窗，不影响主表单

}

function cancel3() {
  open4.value = false
  open3.value = true
  if (userTableRef.value) {
    userTableRef.value.clearSelection(); // 清空表格多选框选中状态
  }
}


const { queryParams3, form1, rules3 } = toRefs(data3)

/** 查询生产退料单行列表 */
async function getList3(nowId) {
  if (!nowId) {
    proxy.$modal.msgError("退料单ID不能为空，无法加载行数据");
    loading3.value = false;
    return; // 终止函数，不向后端发请求
  }
  loading3.value = true;
  try {
    const response = await listLine1(nowId); 
    lineList.value = response.data;
    total4.value = response.total;
  } catch (error) {
    console.error("加载行列表失败：", error);
    proxy.$modal.msgError("加载行数据失败，请重试");
  } finally {
    // 无论成功/失败，都关闭加载状态
    loading3.value = false;
  }
}

// 取消按钮
function cancel4() {
  open3.value = false
  reset3()
}

// 表单重置
function reset3() {
  form1.value = {
    lineId: null,
    rtId: null,
    materialStockId: null,
    itemId: null,
    itemCode: null,
    itemName: null,
    specification: null,
    unitOfMeasure: null,
    quantityRt: null,
    batchCode: null,
    warehouseId: null,
    warehouseCode: null,
    warehouseName: null,
    locationId: null,
    locationCode: null,
    locationName: null,
    areaId: null,
    areaCode: null,
    areaName: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("lineRef")
}



// 多选框选中数据
function handleSelectionChange4(selection) {
  ids3.value = selection.map(item => item.lineId)
  single4.value = selection.length != 1
  multiple4.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd2() {
  reset3()
  form1.value.rtId = currentRtId.value;
  form1.value.warehouseId =cId.value;
  form1.value.warehouseCode =cCode.value;
  form1.value.warehouseName =cName.value;
  form1.value.locationId =qId.value;
  form1.value.locationCode =qCode.value;
  form1.value.locationName =qName.value;
  form1.value.areaId =wId.value;
  form1.value.areaCode =wCode.value;
  form1.value.areaName =wName.value;
  open3.value = true
 console.log(form1.value);
 
  title4.value = "添加生产退料单行"
}

const oldCount=ref()
/** 修改按钮操作 */
function handleUpdate3(row) {
  console.log("row");
  // console.log(row);
  oldCount.value=row.quantityRt  
  reset3()
  
  const _lineId = row.lineId || ids3.value
  getLine(_lineId).then(response => {
    form1.value = response.data
    form1.value.rtId = currentRtId.value;
    open3.value = true
    title4.value = "修改生产退料单行"
  })
}
import {updataliang} from '@/api/line/line'
  const formRef = ref()

  const newCount=ref()
/** 提交按钮 */
function submitForm3() {
console.log("提交");
console.log(form1.value);
//根据id修改仓库数量
  
  formRef.value.validate((valid) => {
    if (valid) {
      if (form1.value.lineId != null) {
        newCount.value=form1.value.quantityRt-oldCount.value
       // console.log(newCount.value);
        updataliang(form1.value.materialStockId,newCount.value)
        updateLine(form1.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open3.value = false
          open.value=true
          getList3(nowId.value)
        })
      } else {
         updataliang(form1.value.materialStockId,form1.value.quantityRt)
        addLine(form1.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open3.value = false
          getList3(nowId.value)
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete3(row) {
  console.log(row.materialStockId);
   console.log(-row.quantityRt);
  const _lineIds = row.lineId || ids3.value
  proxy.$modal.confirm('是否确认删除生产退料单行编号为"' + _lineIds + '"的数据项？').then(function() {
    return delLine(_lineIds)
  }).then(() => {
     updataliang(row.materialStockId,-row.quantityRt)//删除库存量增加
     getList3(nowId.value)

    proxy.$modal.msgSuccess("删除成功")
     open.value=true
  }).catch(() => {
     open.value=true
  })
  

}





import { listIssue, getIssue, delIssue, addIssue, updateIssue,cang ,cang1,qu,wei} from "@/api/issue/issue"
const { proxy } = getCurrentInstance()

const issueList = ref([])
const open = ref(false)
const open2 = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const flag=ref(false)
//选择生产工单
 function kaii() {
    open2.value=true
    // router1.push('/mm')
}
import { listWorkorder } from "@/api/workorder/workorder"

import { ref } from 'vue'

const selectedItem = ref('')
const workorderList = ref([])
const loading1 = ref(true)
const showSearch1 = ref(true)
const ids1 = ref([])
const single1 = ref(true)
const multiple1 = ref(true)
const total1 = ref(0)

const data1 = reactive({
  form: {},
  queryParams1: {
    pageNum: 1,
    pageSize: 10,
    workorderCode: null,
    workorderName: null,
    orderType: null,
    quantity:null,
    orderSource: null,
    productCode: null,
    productName: null,
    productId:null,
    clientCode: null,
    clientName: null,
    requestDate: null,

  },
  
})

const { queryParams1 } = toRefs(data1)
// 绑定的选中值（数组形式，存储各级选中的value）
const value1=ref([])
const options1=ref([])
//查询仓库
cangku()
function cangku(){
  const result=cang();
  result.then(res=>{
     options1.value=res.data  
  })
}
  // 转换后的数据（供级联选择器使用）
const formattedOptions = computed(() => {
  // 递归转换函数：将原始数据转为级联选择器格式
  const convert = (data) => {
    return data.map(item => {
      // 仓库级节点
      const warehouseNode = {
        value: item.warehouseId,  // 仓库ID作为value
        label: item.warehouseName, // 仓库名称作为label
        children: []
      };

      // 处理库区子节点
      if (item.storageLocationList && item.storageLocationList.length) {
        warehouseNode.children = item.storageLocationList.map(location => {
          const locationNode = {
            value: location.locationId,  // 库区ID作为value
            label: location.locationName, // 库区名称作为label
            children: []
          };

          // 处理库位子节点
          if (location.storageAreaList && location.storageAreaList.length) {
            locationNode.children = location.storageAreaList.map(area => ({
              value: area.areaId,  // 库位ID作为value
              label: area.areaName  // 库位名称作为label
            }));
          }

          return locationNode;
        });
      }

      return warehouseNode;
    });
  };
  // 调用转换函数处理原始数据
  return convert(options1.value);
});





/** 查询生产工单列表 */
function getList1() {

  loading1.value = true
  listWorkorder(queryParams1.value).then(response => {
    workorderList.value = response.rows
    total1.value = response.total
    loading1.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery1() {
  queryParams1.value.pageNum = 1
  getList1()
}

/** 重置按钮操作 */
function resetQuery1() {
  proxy.resetForm("queryRef")
  handleQuery1()
}

// 多选框选中数据
function handleSelectionChange1(selection) {
  ids1.value = selection.map(item => item.workorderId)
  single1.value = selection.length != 1
  multiple1.value = !selection.length
    selectedItem.value = selection.length > 0 ? selection[0] : null;

}
const tableRef = ref(null); // 用于获取el-table实例
// 对话框关闭时的处理方法
const handleDialogClose = () => {
  open2.value = false;
  open.value = true;
  if (tableRef.value) {
    tableRef.value.clearSelection(); // 清空表格多选框选中状态
  }
};
// 选中按钮
function confirmSelectedItem() {
  if (!selectedItem.value) {
    proxy.$modal.msgWarning("请选择一个工单");
    return;
  }
  //console.log(selectedItem.value);
  // 将选中的物料信息回填到表单
  form.value.workorderCode = selectedItem.value.workorderCode;
   form.value.workorderId = selectedItem.value.workorderId;
  // 关闭物料选择框，返回工单表单
  open2.value = false;
  open.value = true;

}
//关闭按钮
function cancel1(){
  open2.value = false;
  open.value = true;
  if (tableRef.value) {
    tableRef.value.clearSelection(); // 清空表格多选框选中状态
  }

}
getList1()

// 新增：自动生成编码开关状态
const autoGenerateCode = ref(false)

/** 生成仓库编码（规则：WS-YYYYMMDDHHmmss，如WS-20240520143025） */
function generateWorkshopCode() {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  const second = String(date.getSeconds()).padStart(2, '0')
  const code = `TK-${year}${month}${day}${hour}${minute}${second}`
  form.value.rtCode = code
}

/** 自动生成开关变化事件 */
function handleCodeSwitchChange() {
  
  if (autoGenerateCode.value) {
    generateWorkshopCode()
  } else {
    form.value.rtCode = null  // 关闭时清空手动输入
    
  }
  form.value.warehouseId=value1.value[0]
  console.log(value1.value[0]);

}

// 表单ref（与模板中ref="warehouseRef"对应）
const warehouseRef = ref();
// 对话框关闭时：重置表单 + 关闭开关
function resetDialogForm() {
  // 关闭“自动生成”开关
  autoGenerateCode.value = false;
  // 清除验证状态
  if (warehouseRef.value) {
    warehouseRef.value.clearValidate(); // 清除所有字段验证
  }
  // 清空表单数据
  data.form = {};
  open.value = false;
  value1.value=''
}
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    rtCode: null,
    rtName: null,
    workorderCode: null,
  },
  rules: {
    rtCode: [
      { required: true, message: "退料单编号不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询生产退料列表 */
function getList() {
  loading.value = true
  listIssue(queryParams.value).then(response => {
    issueList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  value1.value=''
  reset()
}

// 表单重置
function reset() {
  form.value = {
    rtId: null,
    rtCode: null,
    rtName: null,
    workorderId: null,
    workorderCode: null,
    warehouseId: null,
    warehouseCode: null,
    warehouseName: null,
    locationId: null,
    locationCode: null,
    locationName: null,
    areaId: null,
    areaCode: null,
    areaName: null,
    rtDate: null,
    status: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("issueRef1")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.rtId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  flag.value=false
  title.value = "添加生产退料"
}
//存储当前id的信息
const currentRtId=ref()
const cId=ref()
const cCode=ref()
const cName=ref()
const qId=ref()
const qCode=ref()
const qName=ref();
const wId=ref();
const wCode=ref();
const wName=ref();
/** 修改按钮操作 */
const nowId=ref()
function handleUpdate(row) {
  value1.value=[row.warehouseId,row.locationId,row.areaId]
  nowId.value=row.rtId;//存储当前单行id

  getList3(row.rtId)
   currentRtId.value = row.rtId;//保存一份
  form1.value.rtId =row.rtId;//存储当前退料单id
// console.log(form1.value.rtId);
    cId.value=row.warehouseId;
    cCode.value=row.warehouseCode;
    cName.value=row.warehouseName;
    qId.value=row.locationId;
    qCode.value=row.locationCode;
    qName.value=row.locationName;
    wId.value=row.areaId;
    wCode.value=row.areaCode;
    wName.value=row.areaName;
  flag.value=true
  reset()
  const _rtId = row.rtId || ids.value
  getIssue(_rtId).then(response => {
    form.value = response.data
    form1.value.warehouseId =row.warehouseId;
    form1.value.warehouseCode =row.warehouseCode;
    form1.value.warehouseName =row.warehouseName;
    form1.value.locationId =row.locationId;
    form1.value.locationCode =row.locationCode;
    form1.value.locationName =row.locationName;
    form1.value.areaId =row.areaId;
    form1.value.areaCode =row.areaCode;
    form1.value.areaName =row.areaName;
    open.value = true
    title.value = "修改生产退料"
  })
}

/** 提交按钮 */
async function submitForm() {

  // 1. 从级联选择器中获取仓库/库区/库位ID（确保数组有值）
  if (!value1.value || value1.value.length < 3) {
    proxy.$modal.msgError("请完整选择仓库位置");
    return; // 未选择完整时终止提交
  }
  
  form.value.warehouseId = value1.value[0];
  form.value.locationId = value1.value[1];
  form.value.areaId = value1.value[2];
  
  try {
    // 2. 等待所有异步请求完成（关键！）
    const [r, r1, r2] = await Promise.all([
      cang1(form.value.warehouseId),    // 查仓库信息
      qu(form.value.locationId),        // 查库区信息
      wei(form.value.areaId)            // 查库位信息
    ]);
    
    // 3. 给表单赋值（此时接口已返回数据）
    form.value.warehouseCode = r.data.warehouseCode;
    form.value.warehouseName = r.data.warehouseName;
    form.value.locationCode = r1.data.locationCode;
    form.value.locationName = r1.data.locationName;
    form.value.areaCode = r2.data.areaCode;
    form.value.areaName = r2.data.areaName;
  
    
    // 4. 验证并提交表单
    proxy.$refs["issueRef1"].validate(valid => {
      if (valid) {
        if (form.value.rtId != null) {
          updateIssue(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addIssue(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
            value1.value = []; // 清空级联选择（数组应置空，而非''）
          });
        }
      }
    });
    
  } catch (error) {
    // 捕获接口请求失败的情况
    console.error("获取仓库/库区/库位信息失败：", error);
    proxy.$modal.msgError("数据加载失败，请重试");
  }
}

/** 删除头按钮操作 */
import {deleteLine} from '@/api/issue/issue'
async function handleDelete(row) {
  const _rtIds = row.rtId || ids.value;
  if (!_rtIds) {
    proxy.$modal.msgWarning("请选择要删除的领料单");
    return;
  }

  // 步骤1：先删除行表数据
  try {
    await deleteLine([_rtIds]); 
    // proxy.$modal.msgSuccess("行表数据删除成功");
  } catch (error) {
    proxy.$modal.msgError("行表删除失败：" + error.message);
    return; // 行表删除失败，终止头表删除
  }

  // 步骤2：再删除头表数据
  proxy.$modal.confirm('是否确认删除生产领料单头编号为"' + _rtIds + '"的数据项？').then(async () => {
    await delIssue(_rtIds);
    getList(); // 刷新列表
    proxy.$modal.msgSuccess("数据删除成功");
  }).catch(() => {});
}
getList()
</script>
